import 'dart:io';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

import '../utils/lf_logger.dart';

class LfReadSql {
  Database? _db;

  Future<Database> get db async {
    _db ??= await _initDb();
    return _db!;
  }

  _initDb() async {
    // databaseFactory = databaseFactoryFfi;
    String path = join(await getDatabasesPath(), "lf_location.db");
    lfLogger.printInfo(info: path);
    bool exists = await databaseExists(path);
    if (!exists) {
      ByteData data =
          await rootBundle.load(join('assets/database', 'lf_location.db'));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      await File(path).writeAsBytes(bytes);
    }

    Database db = await openDatabase(path);
    return db;
  }

  Future close() async {
    var result = _db?.close();
    _db = null;
    return result;
  }
}
